/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.felisberto.serialfwder.socket.server;

import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

/**
 *
 * @author Filipe
 */
public class NettyServer {

    private NioServerSocketChannelFactory factory;
    private LinkedList<NettySession> sessions;
    
    private int port;

    public NettyServer( int port) {
        sessions = new LinkedList<NettySession>();
        this.port = port;

    }
    
    public void startServer() {
        factory = new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);

        bootstrap.setPipelineFactory(new NettyServerPipelineFactory(this));

        bootstrap.bind(new InetSocketAddress(getPort()));
    }

    public void stopServer() {
        if(factory == null) {
            return;
        }

        factory.releaseExternalResources();
    }
    
    public void sessionClosed(NettySession session){
        sessions.remove(session);
    }
    
    public void sendData(String data) {
        for(NettySession s: sessions){
            s.sendPacket(data);
        }
    }
    
    public void newSession(NettySession session){
        sessions.add(session);
    }

    /**
     * @return the port
     */
    public int getPort() {
        return port;
    }
}
